package cn.hc.tool.exec.utils;

import lombok.Getter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 从容器中获取bean工具类
 *
 * @author huangchao E-mail:fengquan8866@163.com
 * @version 创建时间：2024/9/24 17:02
 */
@Component
public class HcSpringBeanUtil implements ApplicationContextAware {

    //spring 容器
    @Getter
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        HcSpringBeanUtil.applicationContext = applicationContext;
    }

    public static Object getBean(String name) throws BeansException {
        return applicationContext.getBean(name);
    }

    public static <T> T getBean(Class<T> t) throws BeansException {
        return applicationContext.getBean(t);
    }

    public static <T> Map<String, T> getBeansOfType(Class<T> t) throws BeansException {
        return applicationContext.getBeansOfType(t);
    }

    public static <T> T getBean(Class<T> t, String name) throws BeansException {
        return applicationContext.getBean(name, t);
    }

    public static void regist(Class<?> t, Object o) {
        DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();
        defaultListableBeanFactory.registerResolvableDependency(t, o);
    }

    public static void regist(String name, Object o) {
        DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();
//        defaultListableBeanFactory.regist(t, o);
    }
}
